<template>
  <div>
    <el-button class="primary" @click="dialogVisible = true"
      >图片识别</el-button
    >
    <div class="home" style="width: 100%; height: 500px">
      <el-dialog title="图片识别" :visible.sync="dialogVisible" width="30%">
        <el-upload
          class="upload-demo"
          :auto-upload="false"
          :on-change="getImgUrl"
          :show-file-list="false"
          list-type="picture"
          action="action"
          :data="{ token: siteInfos.token }"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
        <el-image class="imgspan" :src="imgUrl">
          <div slot="placeholder" class="image-slot">
            加载中<span class="dot">...</span>
          </div>
        </el-image>

        <el-button size="small" type="primary" @click="getTextByImg"
          >识别图片信息</el-button
        >
      </el-dialog>
      <!-- 图片文字识别展示 -->
      <div>
        <!-- {{msg}}
        <hr>
        {{msg1}}
        <hr> -->
        <h3>每一列的数据：</h3>
        <ul>
          <li v-for="item in lines" :key="item">
            {{ item.text.replace(/\s*/g, "") }}
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>
<script>
// 1.引入tesseract.js

import Tesseract from "tesseract.js";
import { mapState } from "vuex";

export default {
  data() {
    return {
      dialogVisible: false,
      //显示上传的图片
      imgUrl: "",
      msg: "",
      msg1: "",
      lines: [],
    };
  },
  computed: {
    ...mapState(["siteInfos"]),
  },
  methods: {
    //点击获取图片路径
    getImgUrl(file) {
      this.imgUrl = file.url;
    },
    //识别图片内容
    getTextByImg() {
      // recognize方法的 第一个参数：图像，第二个：语种
      Tesseract.recognize(
        this.imgUrl,
        "eng+chi_sim"
        //  { logger: m => console.log(m) }
      ).then((d) => {
        //获取每一列的文本信息
        this.lines = d.data.lines;
        //获取权保护文本
        this.msg = d.data.text;
        //去除空格
        this.msg1 = d.data.text.replace(/\s*/g, "");
        //识别完成之后关闭模态框
        this.dialogVisible = false;
      });
    },
  },
};
</script>
<style scoped>
.imgspan {
  width: 100%;
  height: 200px;
}
</style>
